package com.chatplus.application.aiprocessor.platform.image.chatgpt;

import cn.bugstack.openai.executor.model.chatgpt.config.ChatGPTConfig;
import cn.bugstack.openai.executor.parameter.ImageEnum;
import cn.bugstack.openai.executor.parameter.ImageRequest;
import cn.bugstack.openai.executor.parameter.ImageResponse;
import cn.bugstack.openai.executor.parameter.Item;
import cn.bugstack.openai.session.Configuration;
import cn.bugstack.openai.session.OpenAiSession;
import cn.bugstack.openai.session.OpenAiSessionFactory;
import cn.bugstack.openai.session.defaults.DefaultOpenAiSessionFactory;
import com.chatplus.application.aiprocessor.platform.image.ImgAiProcessorService;
import com.chatplus.application.aiprocessor.provider.ImgAiProcessorServiceProvider;
import com.chatplus.application.common.exception.BadRequestException;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.dto.extend.ImgResultDto;
import com.chatplus.application.enumeration.ImgAiPlatformEnum;
import okhttp3.logging.HttpLoggingInterceptor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * ChatGPT 机器人画图处理器
 **/
@Service(value = ImgAiProcessorServiceProvider.SERVICE_NAME_PRE + "OPENAI")
public class ChatGPTImageProcessor extends ImgAiProcessorService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(ChatGPTImageProcessor.class);
    public ImgResultDto process(String prompt) {
        initConfig();
        if (StringUtils.isNotEmpty(getErrMsg())) {
            throw new BadRequestException(getErrMsg());
        }
        try {
            ChatGPTConfig chatGPTConfig = new ChatGPTConfig();
            chatGPTConfig.setApiHost(getApiUrl());
            chatGPTConfig.setApiKey(getApiKeyList().getFirst());
            // 2. 配置文件
            Configuration configuration = new Configuration();
            configuration.setLevel(HttpLoggingInterceptor.Level.BODY);
            configuration.setChatGPTConfig(chatGPTConfig);
            // 3. 会话工厂
            OpenAiSessionFactory factory = new DefaultOpenAiSessionFactory(configuration);
            // 4. 开启会话
            OpenAiSession openAiSession = factory.openSession();

            ImageRequest request = ImageRequest.builder()
                    .prompt(prompt)
                    .model(ImageRequest.Model.DALL_E_3.getCode())
                    .size(ImageEnum.Size.size_1024.getCode())
                    .responseFormat(ImageEnum.ResponseFormat.B64_JSON.getCode())
                    .build();
            ImageResponse imageResponse = openAiSession.genImages(request);
            LOGGER.message("图片生成完成，上传中...").info();
            Item item = imageResponse.getData().getFirst();
            String openUrl = item.getUrl();
            String base64 = item.getB64Json();
            ImgResultDto imgResultDto = new ImgResultDto();
            imgResultDto.setUrl(saveToOss(openUrl, base64));
            imgResultDto.setRevisedPrompt(item.getRevisedPrompt());
            LOGGER.message("图片生成完成，上传完成...").context("imgResultDto", imgResultDto).info();
            return imgResultDto;
        } catch (Exception e) {
            LOGGER.message("图片生成失败").exception(e).error();
            throw new BadRequestException("图片生成失败");
        }
    }

    @Override
    public ImgAiPlatformEnum getChannel() {
        return ImgAiPlatformEnum.DALL_E_3;
    }
}
